import api from '@/api'

const state = {
  account: localStorage.username,
  token: localStorage.token,
  failure_time: localStorage.failure_time,
  permissions: []
}

const getters = {
  isLogin: state => {
    let retn = false
    if (state.token != null) {
      let unix = Date.parse(new Date())
      if (unix < state.failure_time * 1000) {
        retn = true
      }
    }
    return retn
  }
}

const actions = {
  login ({ commit }, data) {
    return new Promise(resolve => {
      // 通过 mock 进行登录
      api.post('/auth/login', data).then(res => {
        let isSuccess_ = false
        if (res.code == 200) {
          commit('setUserData', res.data)
          isSuccess_ = true
        }
        resolve({
          isSuccess: isSuccess_,
          msg: res.msg || ''
        })
      })
    })
  },
  logout ({ commit }) {
    commit('removeUserData')
    commit('menu/invalidRoutes', null, { root: true })
  },
  // 获取我的权限
  getPermissions ({ state, commit }) {
    return new Promise(resolve => {
      // 通过 mock 获取权限
      api.get('/user/getPermissions').then(res => {
        if (res.code == 200) {
          let p = JSON.parse(res.data)
          commit('setPermissions', p)
          resolve(p)

        }
      })

    })
  }
}

const mutations = {
  setUserData (state, data) {
    localStorage.setItem('account', 'admin')
    localStorage.setItem('username', data.username)
    localStorage.setItem('token', data.token)
    localStorage.setItem('failure_time', data.failureTime)
    state.account = data.username
    state.token = data.token
    state.failure_time = data.failureTime
  },
  removeUserData (state) {
    localStorage.removeItem('account')
    localStorage.removeItem('token')
    localStorage.removeItem('failure_time')
    localStorage.removeItem('notice')
    state.account = ''
    state.token = ''
    state.failure_time = ''
  },
  setPermissions (state, permissions) {
    state.permissions = permissions
  }
}

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}
